/**
 * $Id: SGIPReciverThread.java,v 1.4 2006/09/06 08:06:16 martin Exp $
 *
 * Copyright 2005 Skyinfo, Inc. All Rights Reserved.
 */
package com.haoxi.gateway.runner;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.CommonMsgBean;
import com.haoxi.gateway.common.Queue;
import com.haoxi.gateway.connector.Connector;
import com.haoxi.gateway.connector.impl.SGIPDeliverServer;


public class SGIPReciverThread extends Thread {
    public static final int RUNNER_READY = 2;
    public static final int RUNNER_RUNNING = 4;
    public static final int RUNNER_WAITING = 8;
    public static final int RUNNER_DEAD = 16;
    private static final Log log = LogFactory.getLog(SGIPReciverThread.class);
    private boolean alive;
    private int state = RUNNER_READY;
    private Connector conn;
    private Queue queue;
    public static final ThreadGroup tg = new ThreadGroup("watch-thread");
    private CommonMsgBean common;

    public SGIPReciverThread(String name, Connector con, Queue toQueue) {
        super(tg, name);
        this.conn = con;
        queue = toQueue;
        alive = true;
        state = RUNNER_WAITING;
        setDaemon(true);
    }

    public void kill() {
        state = RUNNER_DEAD;
        alive = false;
        // 杀掉此线程后同时将连接数应该减少，让客户端重连
        SGIPDeliverServer.socketcount--;
        log.info("the " + getName() + " is dead!!!");
    }

    // 有任何异常，直接杀掉线程
    public void run() {
        while (alive) {
            try {
                state = RUNNER_RUNNING;
                task();
            } catch (Exception ex) {
                kill();
                log.error("catch an Exception ,the thread is stop", ex);
            } catch (Throwable t) {
                kill();
                log.error("catch an Throwable ,the thread is stop", t);
            }
        }
    }

    public void task() throws Throwable {
        if (conn.isSocketKeepLive()) {
            common = conn.readProtcol();
        } else {
            kill();
        }
        if (common != null) {
            // add to union queue
            // log.debug("receive obj body:" + obj);
            boolean bOK = queue.add(common);
            if (!bOK) {
                log.error("ReciveQueue is full, add failure !!!");
            }
        } else {
            conn.disConnected();
            kill();
        }
    }
//因jdk1.5的不兼容，于dean屏蔽
/*    public int getState() {
        return state;
    }*/
}
